import React, { useState, useEffect } from 'react'
import { Plus, Edit2, Trash2, Save, X } from 'lucide-react'
import { personnelAPI, equipmentAPI } from '../services/api'

const InfoMaintenance = () => {
  // 选项卡状态
  const [activeTab, setActiveTab] = useState('personnel')
  
  // 人员信息状态
  const [personnel, setPersonnel] = useState([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState(null)

  // 设备维护状态
  const [equipment, setEquipment] = useState([])
  const [equipmentLoading, setEquipmentLoading] = useState(false)
  const [equipmentError, setEquipmentError] = useState(null)

  // 编辑状态
  const [editingItem, setEditingItem] = useState(null)
  const [showAddForm, setShowAddForm] = useState(false)
  const [formData, setFormData] = useState({})
  
  // 设备编辑状态
  const [editingEquipment, setEditingEquipment] = useState(null)
  const [showAddEquipmentForm, setShowAddEquipmentForm] = useState(false)
  const [equipmentFormData, setEquipmentFormData] = useState({})

  // 从API加载人员数据
  useEffect(() => {
    loadPersonnel()
  }, [])

  // 加载人员数据
  const loadPersonnel = async () => {
    try {
      setLoading(true)
      setError(null)
      const response = await personnelAPI.getAll()
      setPersonnel(response.results || response)
    } catch (err) {
      setError('加载人员数据失败: ' + err.message)
      console.error('Failed to load personnel:', err)
    } finally {
      setLoading(false)
    }
  }

  // 表格列配置
  const columns = [
    { key: 'id', label: 'ID', required: false, readonly: true },
    { key: 'name', label: '姓名', required: true },
    { key: 'phone', label: '电话', required: false },
    { key: 'group', label: '分组', required: true }
  ]

  // 开始编辑
  const startEdit = (item) => {
    setEditingItem(item.id)
    setFormData({...item})
  }

  // 获取已有分组列表（去重）
  const getExistingGroups = () => {
    const groups = personnel.map(person => person.group)
    return [...new Set(groups)].filter(group => group.trim() !== '')
  }

  // 开始新增
  const startAdd = () => {
    setFormData({ name: '', phone: '', group: '' })
    setShowAddForm(true)
  }

  // 保存编辑
  const saveEdit = async () => {
    // 验证必填字段
    if (!formData.name || !formData.name.trim()) {
      alert('请填写姓名')
      return
    }
    if (!formData.group || !formData.group.trim()) {
      alert('请填写分组')
      return
    }

    try {
      if (editingItem) {
        // 更新现有项
        await personnelAPI.update(editingItem, formData)
        setEditingItem(null)
      } else {
        // 新增项
        await personnelAPI.create(formData)
        setShowAddForm(false)
      }
      
      // 重新加载数据
      await loadPersonnel()
      setFormData({})
    } catch (err) {
      alert('保存失败: ' + err.message)
      console.error('Save failed:', err)
    }
  }

  // 取消编辑
  const cancelEdit = () => {
    setEditingItem(null)
    setShowAddForm(false)
    setFormData({})
  }

  // 删除项
  const deleteItem = async (id) => {
    if (confirm('确定要删除这条记录吗？')) {
      try {
        await personnelAPI.delete(id)
        // 重新加载数据
        await loadPersonnel()
      } catch (err) {
        alert('删除失败: ' + err.message)
        console.error('Delete failed:', err)
      }
    }
  }

  // 设备维护相关功能
  // 加载设备数据
  const loadEquipment = async () => {
    try {
      setEquipmentLoading(true)
      setEquipmentError(null)
      const response = await equipmentAPI.getAll()
      // 确保 equipment 始终是数组
      setEquipment(response?.results || response || [])
    } catch (err) {
      setEquipmentError('加载设备数据失败: ' + err.message)
      console.error('Failed to load equipment:', err)
      // 发生错误时也要确保 equipment 是数组
      setEquipment([])
    } finally {
      setEquipmentLoading(false)
    }
  }

  // 开始编辑设备
  const startEditEquipment = (item) => {
    setEditingEquipment(item.id)
    setEquipmentFormData({...item})
  }

  // 开始新增设备
  const startAddEquipment = () => {
    setEquipmentFormData({ name: '', experiment: '', responsible: '' })
    setShowAddEquipmentForm(true)
  }

  // 保存设备编辑
  const saveEquipmentEdit = async () => {
    // 验证必填字段
    if (!equipmentFormData.name || !equipmentFormData.name.trim()) {
      alert('请填写设备名称')
      return
    }
    if (!equipmentFormData.experiment || !equipmentFormData.experiment.trim()) {
      alert('请填写相关试验')
      return
    }
    if (!equipmentFormData.responsible || !equipmentFormData.responsible.trim()) {
      alert('请填写设备负责人')
      return
    }

    try {
      if (editingEquipment) {
        // 更新现有项
        await equipmentAPI.update(editingEquipment, equipmentFormData)
        setEditingEquipment(null)
      } else {
        // 新增项
        await equipmentAPI.create(equipmentFormData)
        setShowAddEquipmentForm(false)
      }
      
      setEquipmentFormData({})
      await loadEquipment()
    } catch (err) {
      alert('保存失败: ' + err.message)
      console.error('Save failed:', err)
    }
  }

  // 取消设备编辑
  const cancelEquipmentEdit = () => {
    setEditingEquipment(null)
    setShowAddEquipmentForm(false)
    setEquipmentFormData({})
  }

  // 删除设备
  const deleteEquipment = async (id) => {
    if (confirm('确定要删除这条设备记录吗？')) {
      try {
        await equipmentAPI.delete(id)
        await loadEquipment()
      } catch (err) {
        alert('删除失败: ' + err.message)
        console.error('Delete failed:', err)
      }
    }
  }

  // 切换选项卡时加载对应数据
  useEffect(() => {
    if (activeTab === 'equipment' && equipment.length === 0) {
      loadEquipment()
    }
  }, [activeTab])





  // 加载状态显示
  if (loading) {
    return (
      <div className="card">
        <div style={{ textAlign: 'center', padding: '40px' }}>
          <p>正在加载人员数据...</p>
        </div>
      </div>
    )
  }

  // 错误状态显示
  if (error) {
    return (
      <div className="card">
        <div style={{ textAlign: 'center', padding: '40px' }}>
          <p style={{ color: 'red', marginBottom: '16px' }}>{error}</p>
          <button className="btn btn-primary" onClick={loadPersonnel}>
            重新加载
          </button>
        </div>
      </div>
    )
  }

  return (
    <div className="card">
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '24px' }}>
        <h2>信息维护</h2>
      </div>

      {/* 选项卡 */}
      <div style={{ marginBottom: '24px' }}>
        <div style={{ display: 'flex', borderBottom: '1px solid #d9d9d9' }}>
          <button
            onClick={() => setActiveTab('personnel')}
            style={{
              padding: '12px 24px',
              border: 'none',
              background: activeTab === 'personnel' ? '#1890ff' : 'transparent',
              color: activeTab === 'personnel' ? 'white' : '#666',
              borderRadius: '4px 4px 0 0',
              cursor: 'pointer',
              marginRight: '4px'
            }}
          >
            人员管理
          </button>
          <button
            onClick={() => setActiveTab('equipment')}
            style={{
              padding: '12px 24px',
              border: 'none',
              background: activeTab === 'equipment' ? '#1890ff' : 'transparent',
              color: activeTab === 'equipment' ? 'white' : '#666',
              borderRadius: '4px 4px 0 0',
              cursor: 'pointer'
            }}
          >
            设备维护
          </button>
        </div>
      </div>

      {/* 人员管理选项卡内容 */}
      {activeTab === 'personnel' && (
        <div>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '24px' }}>
            <div></div>
            <div style={{ display: 'flex', alignItems: 'center', gap: '16px' }}>
              <button 
                className="btn btn-primary"
                onClick={startAdd}
              >
                <Plus size={16} />
                新增人员
              </button>
            </div>
          </div>

      {/* 新增表单 */}
      {showAddForm && (
        <div style={{ marginBottom: '24px', padding: '20px', background: '#f8f9fa', borderRadius: '8px' }}>
          <h4 style={{ marginBottom: '16px' }}>新增人员</h4>
          <div className="form-grid">
            <div className="form-group">
              <label>姓名<span style={{color: 'red'}}>*</span></label>
              <input
                type="text"
                value={formData.name || ''}
                onChange={(e) => setFormData({...formData, name: e.target.value})}
                required
              />
            </div>
            <div className="form-group">
              <label>电话</label>
              <input
                type="text"
                value={formData.phone || ''}
                onChange={(e) => setFormData({...formData, phone: e.target.value})}
                placeholder="请输入电话号码"
              />
            </div>
            <div className="form-group">
              <label>分组<span style={{color: 'red'}}>*</span></label>
              {getExistingGroups().length > 0 ? (
                <div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>
                  <select
                    value={formData.group || ''}
                    onChange={(e) => setFormData({...formData, group: e.target.value})}
                    style={{ padding: '8px', border: '1px solid #d9d9d9', borderRadius: '4px' }}
                  >
                    <option value="">请选择分组或输入新分组</option>
                    {getExistingGroups().map(group => (
                      <option key={group} value={group}>{group}</option>
                    ))}
                  </select>
                  <input
                    type="text"
                    placeholder="或输入新分组名称"
                    value={formData.group || ''}
                    onChange={(e) => setFormData({...formData, group: e.target.value})}
                    required
                  />
                </div>
              ) : (
                <input
                  type="text"
                  placeholder="请输入分组名称"
                  value={formData.group || ''}
                  onChange={(e) => setFormData({...formData, group: e.target.value})}
                  required
                />
              )}
            </div>
          </div>
          <div style={{ marginTop: '16px', display: 'flex', gap: '8px' }}>
            <button onClick={saveEdit} className="btn btn-primary">
              <Save size={16} />
              保存
            </button>
            <button onClick={cancelEdit} className="btn btn-secondary">
              <X size={16} />
              取消
            </button>
          </div>
        </div>
      )}

      <div style={{ marginBottom: '16px' }}>
        <h3>人员管理</h3>
        <p style={{ color: '#666', fontSize: '14px', margin: '8px 0' }}>
          共 {personnel.length} 条记录
        </p>
      </div>

      <table className="table">
        <thead>
          <tr>
            <th>ID</th>
            <th>姓名</th>
            <th>电话</th>
            <th>分组</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          {personnel.map((item, index) => (
            <tr key={item.id}>
              <td>{index + 1}</td>
              <td>
                {editingItem === item.id ? (
                  <input
                    type="text"
                    value={formData.name || ''}
                    onChange={(e) => setFormData({...formData, name: e.target.value})}
                    style={{ 
                      width: '100%', 
                      padding: '4px 8px', 
                      border: '1px solid #d9d9d9', 
                      borderRadius: '4px' 
                    }}
                  />
                ) : (
                  <span>{item.name}</span>
                )}
              </td>
              <td>
                {editingItem === item.id ? (
                  <input
                    type="text"
                    value={formData.phone || ''}
                    onChange={(e) => setFormData({...formData, phone: e.target.value})}
                    placeholder="请输入电话号码"
                    style={{ 
                      width: '100%', 
                      padding: '4px 8px', 
                      border: '1px solid #d9d9d9', 
                      borderRadius: '4px' 
                    }}
                  />
                ) : (
                  <span>{item.phone || '-'}</span>
                )}
              </td>
              <td>
                {editingItem === item.id ? (
                  getExistingGroups().length > 0 ? (
                    <div style={{ display: 'flex', flexDirection: 'column', gap: '4px' }}>
                      <select
                        value={formData.group || ''}
                        onChange={(e) => setFormData({...formData, group: e.target.value})}
                        style={{ 
                          width: '100%', 
                          padding: '4px 8px', 
                          border: '1px solid #d9d9d9', 
                          borderRadius: '4px',
                          fontSize: '12px'
                        }}
                      >
                        <option value="">选择分组</option>
                        {getExistingGroups().map(group => (
                          <option key={group} value={group}>{group}</option>
                        ))}
                      </select>
                      <input
                        type="text"
                        placeholder="或输入新分组"
                        value={formData.group || ''}
                        onChange={(e) => setFormData({...formData, group: e.target.value})}
                        style={{ 
                          width: '100%', 
                          padding: '4px 8px', 
                          border: '1px solid #d9d9d9', 
                          borderRadius: '4px',
                          fontSize: '12px'
                        }}
                      />
                    </div>
                  ) : (
                    <input
                      type="text"
                      value={formData.group || ''}
                      onChange={(e) => setFormData({...formData, group: e.target.value})}
                      style={{ 
                        width: '100%', 
                        padding: '4px 8px', 
                        border: '1px solid #d9d9d9', 
                        borderRadius: '4px' 
                      }}
                    />
                  )
                ) : (
                  <span>{item.group}</span>
                )}
              </td>
              <td>
                {editingItem === item.id ? (
                  <div style={{ display: 'flex', gap: '4px' }}>
                    <button 
                      onClick={saveEdit}
                      style={{ 
                        border: 'none', 
                        background: '#27ae60', 
                        color: 'white',
                        padding: '4px 8px',
                        borderRadius: '4px',
                        cursor: 'pointer',
                        fontSize: '12px'
                      }}
                    >
                      保存
                    </button>
                    <button 
                      onClick={cancelEdit}
                      style={{ 
                        border: 'none', 
                        background: '#95a5a6', 
                        color: 'white',
                        padding: '4px 8px',
                        borderRadius: '4px',
                        cursor: 'pointer',
                        fontSize: '12px'
                      }}
                    >
                      取消
                    </button>
                  </div>
                ) : (
                  <div style={{ display: 'flex', gap: '8px', alignItems: 'center' }}>
                    <button onClick={() => startEdit(item)} className="btn-icon" title="编辑">
                      <Edit2 size={16} />
                    </button>
                    <button onClick={() => deleteItem(item.id)} className="btn-icon btn-danger" title="删除">
                      <Trash2 size={16} />
                    </button>
                  </div>
                )}
              </td>
            </tr>
          ))}
        </tbody>
      </table>

          {personnel.length === 0 && (
            <div style={{ textAlign: 'center', padding: '40px', color: '#999' }}>
              暂无人员记录
            </div>
          )}
        </div>
      )}

      {/* 设备维护选项卡内容 */}
      {activeTab === 'equipment' && (
        <div>
          {equipmentLoading ? (
            <div style={{ textAlign: 'center', padding: '40px' }}>
              <p>正在加载设备数据...</p>
            </div>
          ) : equipmentError ? (
            <div style={{ textAlign: 'center', padding: '40px' }}>
              <p style={{ color: 'red', marginBottom: '16px' }}>{equipmentError}</p>
              <button className="btn btn-primary" onClick={loadEquipment}>
                重新加载
              </button>
            </div>
          ) : (
            <>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '24px' }}>
                <div></div>
                <div style={{ display: 'flex', alignItems: 'center', gap: '16px' }}>
                  <button 
                    className="btn btn-primary"
                    onClick={startAddEquipment}
                  >
                    <Plus size={16} />
                    新增设备
                  </button>
                </div>
              </div>

              {/* 新增设备表单 */}
              {showAddEquipmentForm && (
                <div style={{ marginBottom: '24px', padding: '20px', background: '#f8f9fa', borderRadius: '8px' }}>
                  <h4 style={{ marginBottom: '16px' }}>新增设备</h4>
                  <div className="form-grid">
                    <div className="form-group">
                      <label>试验设备名称<span style={{color: 'red'}}>*</span></label>
                      <input
                        type="text"
                        value={equipmentFormData.name || ''}
                        onChange={(e) => setEquipmentFormData({...equipmentFormData, name: e.target.value})}
                        placeholder="请输入设备名称"
                        required
                        style={{ height: '36px' }}
                      />
                    </div>
                    <div className="form-group">
                      <label>相关试验<span style={{color: 'red'}}>*</span></label>
                      <input
                        type="text"
                        value={equipmentFormData.experiment || ''}
                        onChange={(e) => setEquipmentFormData({...equipmentFormData, experiment: e.target.value})}
                        placeholder="请输入相关试验"
                        required
                        style={{ height: '36px' }}
                      />
                    </div>
                    <div className="form-group">
                      <label>设备负责人<span style={{color: 'red'}}>*</span></label>
                      <input
                        type="text"
                        list="personnel-list"
                        value={equipmentFormData.responsible || ''}
                        onChange={(e) => setEquipmentFormData({...equipmentFormData, responsible: e.target.value})}
                        placeholder="请输入或选择负责人"
                        required
                        style={{ height: '36px' }}
                      />
                      <datalist id="personnel-list">
                        {personnel.map(person => (
                          <option key={person.id} value={person.name} />
                        ))}
                      </datalist>
                    </div>
                  </div>
                  <div style={{ marginTop: '16px', display: 'flex', gap: '8px' }}>
                    <button onClick={saveEquipmentEdit} className="btn btn-primary">
                      <Save size={16} />
                      保存
                    </button>
                    <button onClick={cancelEquipmentEdit} className="btn btn-secondary">
                      <X size={16} />
                      取消
                    </button>
                  </div>
                </div>
              )}

              <div style={{ marginBottom: '16px' }}>
                <h3>设备维护</h3>
                <p style={{ color: '#666', fontSize: '14px', margin: '8px 0' }}>
                  共 {Array.isArray(equipment) ? equipment.length : 0} 条记录
                </p>
              </div>

              {/* 为编辑模式提供人员选择建议 */}
              <datalist id="personnel-list-edit">
                {personnel.map(person => (
                  <option key={person.id} value={person.name} />
                ))}
              </datalist>

              <table className="table">
                <thead>
                  <tr>
                    <th>序号</th>
                    <th>试验设备名称</th>
                    <th>相关试验</th>
                    <th>设备负责人</th>
                    <th>操作</th>
                  </tr>
                </thead>
                <tbody>
                  {Array.isArray(equipment) && equipment.map((item, index) => (
                    <tr key={item.id}>
                      <td>{index + 1}</td>
                      <td>
                        {editingEquipment === item.id ? (
                          <input
                            type="text"
                            value={equipmentFormData.name || ''}
                            onChange={(e) => setEquipmentFormData({...equipmentFormData, name: e.target.value})}
                            style={{ 
                              width: '100%', 
                              padding: '4px 8px', 
                              border: '1px solid #d9d9d9', 
                              borderRadius: '4px',
                              height: '32px'
                            }}
                          />
                        ) : (
                          <span>{item.name}</span>
                        )}
                      </td>
                      <td>
                        {editingEquipment === item.id ? (
                          <input
                            type="text"
                            value={equipmentFormData.experiment || ''}
                            onChange={(e) => setEquipmentFormData({...equipmentFormData, experiment: e.target.value})}
                            style={{ 
                              width: '100%', 
                              padding: '4px 8px', 
                              border: '1px solid #d9d9d9', 
                              borderRadius: '4px',
                              height: '32px'
                            }}
                          />
                        ) : (
                          <span>{item.experiment}</span>
                        )}
                      </td>
                      <td>
                        {editingEquipment === item.id ? (
                          <input
                            type="text"
                            list="personnel-list-edit"
                            value={equipmentFormData.responsible || ''}
                            onChange={(e) => setEquipmentFormData({...equipmentFormData, responsible: e.target.value})}
                            placeholder="请输入或选择负责人"
                            style={{ 
                              width: '100%', 
                              padding: '4px 8px', 
                              border: '1px solid #d9d9d9', 
                              borderRadius: '4px',
                              height: '32px'
                            }}
                          />
                        ) : (
                          <span>{item.responsible}</span>
                        )}
                      </td>
                      <td>
                        {editingEquipment === item.id ? (
                          <div style={{ display: 'flex', gap: '4px' }}>
                            <button 
                              onClick={saveEquipmentEdit}
                              style={{ 
                                border: 'none', 
                                background: '#27ae60', 
                                color: 'white',
                                padding: '4px 8px',
                                borderRadius: '4px',
                                cursor: 'pointer',
                                fontSize: '12px'
                              }}
                            >
                              保存
                            </button>
                            <button 
                              onClick={cancelEquipmentEdit}
                              style={{ 
                                border: 'none', 
                                background: '#95a5a6', 
                                color: 'white',
                                padding: '4px 8px',
                                borderRadius: '4px',
                                cursor: 'pointer',
                                fontSize: '12px'
                              }}
                            >
                              取消
                            </button>
                          </div>
                        ) : (
                          <div style={{ display: 'flex', gap: '8px', alignItems: 'center' }}>
                            <button onClick={() => startEditEquipment(item)} className="btn-icon" title="编辑">
                              <Edit2 size={16} />
                            </button>
                            <button onClick={() => deleteEquipment(item.id)} className="btn-icon btn-danger" title="删除">
                              <Trash2 size={16} />
                            </button>
                          </div>
                        )}
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>

              {equipment.length === 0 && (
                <div style={{ textAlign: 'center', padding: '40px', color: '#999' }}>
                  暂无设备记录
                </div>
              )}
            </>
          )}
        </div>
      )}
    </div>
  )
}

export default InfoMaintenance